// 首先引入axios和上一步封装的cookie方法
import axios, { AxiosInstance } from "axios";
import Cookies from "js-cookie";
import {userInfo} from "../api/api";

function syncHttpSendTokenFun() {
    const params = new URLSearchParams();
    const refreshToken = Cookies.get('refreshToken');
    let responseText = '';
    if (refreshToken != undefined && refreshToken != '') {
        const client_id = window.location.hostname;
        params.append('grant_type', "refresh_token");
        params.append('client_id', client_id);
        params.append('refresh_token', refreshToken);

        let xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {
                responseText = xhr.responseText;
            } else {
                responseText = '';
                console.log('Request was unsuccessful', xhr.status);
            }
        }
        xhr.open('post', 'http://u.xlmediawatch.com/auth/realms/xlplatform/protocol/openid-connect/token', false);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
        xhr.send(params)
    }
    return responseText;
}

export class Interceptors {
    instance: AxiosInstance;
    constructor() {
        this.instance = axios.create({
            baseURL: "http://api.xlmediawatch.com/INEWSAPI/inews",
            timeout: 60000,
            headers: {
                'Content-Type': 'application/json'
            }
        });
        // 请求接口拦截器
        this.instance.interceptors.request.use(
            async (config) => {
                let token = syncHttpSendTokenFun();
                var millisecond = new Date().getTime();
                var expiresTime = new Date(millisecond + 60 * 1000 * 15);

                // 判断一下是否有cookie 如果有的话则把cookie放入请求头中
                if (token !== '') {
                    Cookies.set('refreshToken', JSON.parse(token)['refresh_token'], {
                        expires: expiresTime,
                    });
                    if(config.url !== '/user'){
                        // 获取个人信息的接口不再进入  不然会死循环
                        let resultUser = await userInfo()
                        if (resultUser.data.status === 0) {
                            sessionStorage.setItem('userInfo', resultUser.data.data)
                        }
                    }

                    // @ts-ignore
                    config.headers['Authorization'] = 'bearer ' + JSON.parse(token)['access_token']
                    // @ts-ignore
                    // config.headers['orgId'] = 9542
                }
                return config;
            },
            (err) => {
                console.error(err);
            }
        );

        // 响应拦截器
        // this.instance.interceptors.response.use(
        //     (response) => {
        //         const res = response.data;
        //         if (!response.status.toString().startsWith("2") || res.code === -1) {
        //             // 如果状态码不是2开头或者接口code返回-1 则是返回错误信息
        //             console.error("系统错误，请检查API是否正常！");
        //             return;
        //         }
        //         if (res.code !== 0) {
        //             if (res.code === -3) {
        //                 console.error("登录过期");
        //                 removeToken();
        //             } else {
        //                 if (res.msg) {
        //                     console.error(res.msg);
        //                 }
        //             }
        //             return Promise.resolve(res);
        //         } else {
        //             // 返回成功则把token存储一下
        //             const headers = response.headers;
        //             const token = headers.token;
        //             const refresh_token = headers["refresh-token"];
        //             if (token && refresh_token) {
        //                 setToken(token);
        //                 setRefreshToken(refresh_token);
        //             }
        //             return res;
        //         }
        //     },
        //     (error) => {
        //         if (error.message === "Request failed with status code 500") {
        //             console.error("系统错误，请检查API是否正常！");
        //             return;
        //         }
        //         let code = -110;
        //         if (error && error.response && error.response.status) {
        //             code = error.response.status;
        //             // 登陆过期
        //             if (code === 401 || code === -3) {
        //                 removeToken();
        //             }
        //         } else {
        //             console.error(error.message);
        //         }
        //         const err = { errCode: -110, errMsg: error.message || "Error" };
        //         return Promise.resolve(err);
        //     }
        // );
    }
    // 返回一下
    getInterceptors() {
        return this.instance;
    }
}